package SocketBaseTest;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * Created by yexuan on 2018/3/22.
 * 实现键盘发送聊天功能
 */
public class ChatSend {
    public static void main(String[] args) throws Exception {
        DatagramSocket dgs = new DatagramSocket();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        byte[] bytes = new byte[1024];
        String line = null;
        while ((line = br.readLine())!=null){  //readLine 阻塞方法
            if("886".equals(line)){
                break;
            }
            byte[] buff = line.getBytes();
            DatagramPacket dgp = new DatagramPacket(buff,buff.length, InetAddress.getLocalHost(),1234);
            dgs.send(dgp);
        }
        br.close();
    }
}

class ChatReceive{
    public static void main(String[] args)throws Exception  {
        DatagramSocket dgs = new DatagramSocket(1234);
        while(true){
            byte[] bytes = new byte[1024];
            DatagramPacket dgp = new DatagramPacket(bytes,bytes.length);
            dgs.receive(dgp);  //receive 阻塞方法
            System.out.println(dgp.getAddress().getHostAddress()+":"+new String(dgp.getData(),0,dgp.getLength()));
        }

    }
}
